<template>
  <div class="exchange-container">
    <el-card class="exchange-card">
      <h2>{{ t('exchange.title') }}</h2>
      <div v-if="!exchangeCodeValidated">
        <el-form :model="exchangeForm" :rules="rules" ref="exchangeFormRef" label-width="120px">
          <el-form-item :label="t('exchange.code')" prop="code">
            <el-input 
              v-model="exchangeForm.code" 
              :placeholder="t('exchange.enterCode')"
              @keyup.enter="validateExchangeCode"
            ></el-input>
          </el-form-item>
          <el-form-item :label="t('exchange.password')" prop="password">
            <el-input 
              v-model="exchangeForm.password" 
              type="password"
              :placeholder="t('exchange.enterPassword')"
              @keyup.enter="validateExchangeCode"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <div style="text-align: right; width: 100%; margin-bottom: 10px;">
              <a href="#" @click.prevent="showForgotPasswordDialog" style="color: #409EFF; font-size: 14px;">{{ t('exchange.contactSupport') }}</a>
            </div>
            <el-button 
              type="primary" 
              @click="validateExchangeCode" 
              :loading="validating"
              style="width: 100%"
            >
              {{ t('exchange.validateButton') }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <div v-else-if="exchangeData">
        <h3>{{ t('exchange.validationSuccess') }}</h3>
        <p><strong>{{ t('exchange.code') }}:</strong> {{ exchangeData.exchangeCode.code }}</p>
        <p><strong>{{ t('exchange.expirationDate') }}:</strong> {{ exchangeData.exchangeCode.expirationDate }}</p>
        
        <h4>{{ t('exchange.productDetails') }}</h4>
        <div class="products-list">
          <el-card 
            v-for="product in exchangeData.products" 
            :key="product.id" 
            class="product-card"
          >
            <div class="product-info">
              <h5>{{ product.name }}</h5>
              <p>{{ product.description }}</p>
              <p><strong>{{ t('exchange.productPrice') }}:</strong> ${{ product.price }}</p>
            </div>
          </el-card>
        </div>
        
        <h4>{{ t('exchange.deliveryInformation') }}</h4>
        <el-form :model="deliveryForm" :rules="deliveryRules" ref="deliveryFormRef" label-width="120px">
          <el-form-item :label="t('exchange.customerName')" prop="customerName">
            <el-input v-model="deliveryForm.customerName" :placeholder="t('exchange.enterCustomerName')"></el-input>
          </el-form-item>
          <el-form-item :label="t('exchange.customerPhone')" prop="customerPhone">
            <el-input v-model="deliveryForm.customerPhone" :placeholder="t('exchange.enterCustomerPhone')"></el-input>
          </el-form-item>
          <el-form-item :label="t('exchange.customerEmail')" prop="customerEmail">
            <el-input v-model="deliveryForm.customerEmail" :placeholder="t('exchange.enterCustomerEmail')"></el-input>
          </el-form-item>
          <el-form-item :label="t('exchange.deliveryType')" prop="deliveryType">
            <el-radio-group v-model="deliveryForm.deliveryType">
              <el-radio label="SHIP">{{ t('exchange.shipToAddress') }}</el-radio>
              <el-radio label="PICKUP">{{ t('exchange.pickupInStore') }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item 
            v-if="deliveryForm.deliveryType === 'SHIP'" 
            :label="t('exchange.shippingAddress')" 
            prop="shippingAddress"
          >
            <el-input 
              v-model="deliveryForm.shippingAddress" 
              type="textarea" 
              :rows="3"
              :placeholder="t('exchange.enterShippingAddress')"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button 
              type="success" 
              @click="completeExchange" 
              :loading="completing"
              style="width: 100%"
            >
              {{ t('exchange.completeButton') }}
            </el-button>
          </el-form-item>
        </el-form>
        
        <el-button @click="resetExchange" style="margin-top: 10px; width: 100%">
          {{ t('exchange.enterAnotherCode') }}
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { ref, reactive } from 'vue'
import { useI18n } from 'vue-i18n'

export default {
  name: 'CustomerExchange',
  setup() {
    const { t } = useI18n()
    const validating = ref(false)
    const completing = ref(false)
    const exchangeCodeValidated = ref(false)
    const exchangeData = ref(null)
    
    const exchangeForm = reactive({
      code: '',
      password: ''
    })
    
    const deliveryForm = reactive({
      customerName: '',
      customerPhone: '',
      customerEmail: '',
      deliveryType: 'SHIP', // Default to shipping
      shippingAddress: ''
    })
    
    const rules = {
      code: [
        { required: true, message: t('exchange.enterCode'), trigger: 'blur' },
        { min: 6, message: t('exchange.codeMinLength'), trigger: 'blur' }
      ],
      password: [
        { required: true, message: t('exchange.enterPassword'), trigger: 'blur' },
        { min: 6, message: t('exchange.passwordMinLength'), trigger: 'blur' }
      ]
    }
    
    const deliveryRules = {
      customerName: [
        { required: true, message: t('exchange.enterCustomerName'), trigger: 'blur' }
      ],
      customerPhone: [
        { required: true, message: t('exchange.enterCustomerPhone'), trigger: 'blur' }
      ],
      customerEmail: [
        { required: true, message: t('exchange.enterCustomerEmail'), trigger: 'blur' },
        { type: 'email', message: t('exchange.invalidEmail'), trigger: 'blur' }
      ],
      shippingAddress: [
        { required: true, message: t('exchange.enterShippingAddress'), trigger: 'blur' }
      ]
    }
    
    const validateExchangeCode = async () => {
      try {
        validating.value = true
        
        // In a real application, you would make an API call to validate the exchange code and password
        // For now, using a mock implementation
        const response = await mockValidateCodeApi(exchangeForm.code, exchangeForm.password)
        
        if (response.success) {
          exchangeData.value = response
          exchangeCodeValidated.value = true
          ElMessage.success(t('exchange.validationSuccess'))
        } else {
          ElMessage.error(response.message || t('exchange.validationFailed'))
        }
      } catch (error) {
        console.error('Validation error:', error)
        ElMessage.error(t('exchange.errorOccurred'))
      } finally {
        validating.value = false
      }
    }
    
    const completeExchange = async () => {
      try {
        completing.value = true
        
        // Validate delivery form
        // In a real app, you'd validate the form with Element Plus
        
        // In a real application, you would make an API call to complete the exchange
        // For now, using a mock implementation
        const response = await mockCompleteExchangeApi({
          ...deliveryForm,
          code: exchangeForm.code,
          password: exchangeForm.password  // Include password for verification
        })
        
        if (response.success) {
          ElMessage.success(t('exchange.exchangeSuccess'))
          ElMessage.info(`${t('exchange.orderNumber')} ${response.order.orderNumber}`)
          // Optionally redirect to order tracking page
          // router.push(`/track/${response.order.orderNumber}`)
        } else {
          ElMessage.error(response.message || t('exchange.exchangeFailed'))
        }
      } catch (error) {
        console.error('Exchange completion error:', error)
        ElMessage.error(t('exchange.errorExchange'))
      } finally {
        completing.value = false
      }
    }
    
    const resetExchange = () => {
      exchangeCodeValidated.value = false
      exchangeData.value = null
      exchangeForm.code = ''
      exchangeForm.password = ''
    }
    
    const showForgotPasswordDialog = () => {
      // In a real application, this would show a dialog to help users recover their password
      // For now, show an informational message
      ElMessage.info(t('exchange.contactSupport'))
    }
    
    // Mock API calls - in a real app, replace with actual API calls
    const mockValidateCodeApi = (code, password) => {
      return new Promise((resolve) => {
        setTimeout(() => {
          // In a real application, both code and password would be validated
          // For this mock, we'll validate with a specific code and password combination
          if (code === 'VALID123' && password === 'password123') {
            resolve({
              success: true,
              exchangeCode: {
                code: 'VALID123',
                expirationDate: '2024-12-31'
              },
              products: [
                {
                  id: 1,
                  name: 'Sample Product',
                  description: 'This is a sample product for exchange',
                  price: '19.99'
                }
              ]
            })
          } else if (code !== 'VALID123') {
            resolve({
              success: false,
              message: t('exchange.invalidCode')
            })
          } else if (password !== 'password123') {
            resolve({
              success: false,
              message: t('exchange.invalidPassword')
            })
          } else {
            resolve({
              success: false,
              message: t('exchange.invalidCredentials')
            })
          }
        }, 500)
      })
    }
    
    const mockCompleteExchangeApi = (data) => {
      // Using the data parameter to simulate processing the order
      console.log('Processing exchange with data:', data)
      // In a real application, the server would verify the password again
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({
            success: true,
            order: {
              orderNumber: 'ORD' + Date.now().toString().substr(-8)
            },
            message: t('exchange.exchangeCompleted')
          })
        }, 800)
      })
    }
    
    return {
      t,
      validating,
      completing,
      exchangeCodeValidated,
      exchangeData,
      exchangeForm,
      deliveryForm,
      rules,
      deliveryRules,
      validateExchangeCode,
      completeExchange,
      resetExchange,
      showForgotPasswordDialog
    }
  }
}
</script>

<style scoped>
.exchange-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding: 20px;
  min-height: 100vh;
  background-color: #f9f9f9;
}

.exchange-card {
  max-width: 600px;
  width: 100%;
  margin: 20px auto;
}

.products-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  margin: 20px 0;
}

.product-card {
  margin-bottom: 10px;
}

.product-info h5 {
  margin: 0 0 10px 0;
  color: #303133;
}

.product-info p {
  margin: 5px 0;
  color: #606266;
}
</style>